﻿using AutoMapper;
using MediatR;
using System.Transactions;
using Traceability.App.API.Application.Command.Basic;
using Traceability.App.Domain.Entities;
using Traceability.App.ErrorCode;
using Traceability.App.Infrastructure.Interface;

namespace Traceability.App.API.Application.Handler.Basic
{
    /// <summary>
    /// 创建溯源管理基本信息请求命令处理类
    /// </summary>
    public class CreateBasic_TraceabilityHandler:IRequestHandler<CreateBasic_TraceabilityCommand,ApiResult<int>>
    {
        IBaseRepository<Basic_Traceability> basicRep;
        IMapper mapper;

        public CreateBasic_TraceabilityHandler(IBaseRepository<Basic_Traceability> basicRep, IMapper mapper)
        {
            this.basicRep = basicRep;
            this.mapper = mapper;
        }

        public Task<ApiResult<int>> Handle(CreateBasic_TraceabilityCommand request, CancellationToken cancellationToken)
        {
            try
            {
                ApiResult<int> res = new ApiResult<int>();
                var basic=basicRep.GetAll().Where(x=>x.Production_Batch==request.production_Batch).FirstOrDefault();
                if(basic!=null)
                {
                    res.Msg = "生产批次重复，无法进行添加";
                    res.Code=ApiEnum.Fail;
                    return Task.FromResult(res);
                }
                int r = 0;
                var basicmapper = mapper.Map<Basic_Traceability>(request);
                basicmapper.Creator = "张三";
                basicmapper.CreateTime = DateTime.Now;
                r = basicRep.CreateAsync(basicmapper).Result;
                

                if(r>0)
                {
                    res.Msg = "创建成功";
                    res.Code=ApiEnum.Success;
                    res.Data = r;
                }
                else
                {
                    res.Msg = "创建失败";
                    res.Code = ApiEnum.Fail;
                }
                return Task.FromResult(res);
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
